package hub

import (
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/streadway/amqp"
	"time"
)

// Pub 生产者 fanout群发 direct、topic
func (m *Message) Pub() {
	// 连接信道
	ch, err := conn.Channel()
	if err != nil {
		return
	}
	// 选择交换机
	err = ch.ExchangeDeclare(
		m.Exchange, // name
		m.Kind,     // type  fanout、direct:、topic
		false,      // 是否持久化
		false,      // auto-deleted
		false,      // internal
		false,      // no-wait
		nil,        // arguments
	)
	if err != nil {
		return
	}
	// 生产消息
	c := m.Connect
	for {
		_, body, err := c.readPump()

		// todo 在消息被放入消息队列前进行验证, 如果被禁言了, continue

		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				// 玩家主动断开了连接
				fmt.Println("玩家主动断开了连接")
				// todo 向交换机里注入消息, 广播当前人数
			}
			break
		}
		err = ch.Publish(
			m.Exchange, // exchange
			m.Routing,  // routing key
			false,      // mandatory
			false,      // immediate
			amqp.Publishing{
				ContentType: "application/json",
				Body:        body,
			})
	}
}


func (c *Connect) readPump() (messageType int, p []byte, err error) {
	c.Ws.SetReadLimit(512)
	_ = c.Ws.SetReadDeadline(time.Now().Add(30 * time.Second))
	c.Ws.SetPongHandler(func(string) error { _ = c.Ws.SetReadDeadline(time.Now().Add(30 * time.Second)); return nil})
	return c.Ws.ReadMessage()
}
